<?php
namespace App\Common\Lib\Com;

use App\Common as com;
use App\Common\Lib\Com\StaticPool as thisStaticPool;

class StaticPool extends com\Lib\LibBase {

	private static array $makeStatic = [];

	/**
	 * 创建单列
	 * @param $poolName
	 * @param $fn
	 * @return mixed
	 * @throws \Throwable
	 */
	public static function getStatic( $poolName, $fn ) {
		if( ! array_key_exists( $poolName, self::$makeStatic ) ){
			// 先把坑占了,防止协程切换重复创建
			self::$makeStatic[ $poolName ] = null;
			//
			try{
				self::$makeStatic[ $poolName ] = call_user_func( $fn );
			} catch( \Throwable $e ){
				// 异常处理
				unset( self::$makeStatic[ $poolName ] );
				//
				throw $e;
			}
		}
		// 未初始完毕
		if( self::$makeStatic[ $poolName ] === null ){
			while( true ){
				\Swoole\Coroutine::sleep( 0.001 );
				//
				if( self::$makeStatic[ $poolName ] !== null ){
					break;
				}
			}
		}
		//
		return self::$makeStatic[ $poolName ];
	}

}
